import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 路由懒加载
const Tabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('@/views/Home')
const Question = () => import('@/views/Question')
const Video = () => import('@/views/Video')
const User = () => import('@/views/User')
const Article = () => import('@/views/Article')
const Login = () => import('@/views/Login')
Vue.use(VueRouter)
// 配置路由地址
const routes = [
  {
    path: '/',
    components: { default: Home, tabbar: Tabbar }
  },
  {
    path: '/question',
    components: { default: Question, tabbar: Tabbar }
  },
  {
    path: '/video',
    components: { default: Video, tabbar: Tabbar }
  },
  {
    path: '/user',
    components: { default: User, tabbar: Tabbar }
  },
  {
    path: '/article',
    component: Article
  },
  {
    path: '/login',
    component: Login
  }

]

const router = new VueRouter({
  routes
})
// 前置路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token // 尝试在本地获取token
  if (!token && to.path.startsWith('/user')) { // 没有token且去往user开头的路径时
    return next('/login?returnUrl=' + encodeURIComponent(to.fullPath)) // 返回登录页或者原页面
  } else { // 其他情况所有页面放行
    next()
  }
})
export default router
